﻿using Corina.Commands;
using Corina.Common;
using Corina.Enumerations;
using Corina.Infrastructure;
using Corina.Win.Interface;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Input;
using System.Collections.ObjectModel;
using System.Windows.Media;

namespace Corina.Addins.Xiami
{
    [Export(typeof(IView))]
    public class XiamiViewmodel : BaseClass, IView
    {
        WebClient client = new WebClient();
        MediaPlayer player = new MediaPlayer();
        public XiamiViewmodel()
        {
            Title = "虾米音乐";
            UriString = "XiamiView";
            UriType = Enumerations.UriType.InApp;
            Icon = "ICON_MEMORY_CARD";

            client.DownloadStringCompleted += DownloadStringCompleted;
            player.MediaOpened+=MediaOpened;
        }

        private void MediaOpened(object sender, EventArgs e)
        {
            player.Play();
        }

        private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                List<MusicInfo> objs = JsonHelper.Parse<List<MusicInfo>>(e.Result);
                try
                {
                    ResultCollection = new ObservableCollection<MusicInfo>(objs);
                }
                catch {
                    ResultCollection = new ObservableCollection<MusicInfo>();
                }
            }
        }

        #region Fields
        private int _pageIndex = 0;
        private string _title;
        private string _uriString;
        private UriType _uriType = UriType.OutApp;
        private string _icon;
        private int _index = 0;
        #endregion

        #region Properties
        public int PageIndex
        {
            get { return _pageIndex; }
            set
            {
                _pageIndex = value;
                RaisePropertyChanged(() => PageIndex);
            }
        }

        public string Icon
        {
            get { return _icon; }
            set
            {
                _icon = value;
                RaisePropertyChanged(() => Icon);
            }
        }

        public string Title
        {
            get { return _title; }
            set
            {
                _title = value;
                RaisePropertyChanged(() => Title);
            }
        }

        public string UriString
        {
            get { return _uriString; }
            set
            {
                _uriString = value;
                RaisePropertyChanged(() => UriString);
                RaisePropertyChanged(() => FullUrl);
            }
        }

        public UriType UriType
        {
            get { return _uriType; }
            set
            {
                _uriType = value;
                RaisePropertyChanged(() => UriType);
                RaisePropertyChanged(() => FullUrl);
            }
        }

        public string FullUrl
        {
            get
            {
                return UrlPrefix<XiamiViewmodel>.Prefixs.FirstOrDefault(k => k.Key == UriType).Value + "Views/" + UriString + ".xaml";
            }
        }

        public int Index
        {
            get { return _index; }
            set
            {
                _index = value;
                RaisePropertyChanged(() => Index);
            }
        }
        #endregion

        #region Search
        private string _keywords = string.Empty;
        public string Keywords
        {
            get { return _keywords; }
            set
            {
                _keywords = value;
                RaisePropertyChanged(() => Keywords);
                RaisePropertyChanged(() => FullUri);
                RaisePropertyChanged(() => SearchCommand);
            }
        }

        public string _url = "http://www.xiami.com/web/search-songs?spm=0.0.0.0.Yur0SB&key=";
        public string Url
        {
            get { return _url; }
            set
            {
                _url = value;
                RaisePropertyChanged(() => Url);
                RaisePropertyChanged(() => FullUri);
            }
        }

        private int _currentIndex = 1;
        public int CurrentIndex
        {
            get { return _currentIndex; }
            set {
                _currentIndex = value;
                RaisePropertyChanged(() => CurrentIndex);
                RaisePropertyChanged(() => FullUri);
                RaisePropertyChanged(() => PreviousCommand);
            }
        }

        public string FullUri
        {
            get { return string.Format("{0}{1}&page={2}", Url, HttpUtility.HtmlEncode(Keywords), CurrentIndex); }
        }
        #endregion

        #region Collection
        private ObservableCollection<MusicInfo> _resultCollection;
        public ObservableCollection<MusicInfo> ResultCollection
        {
            get { return _resultCollection; }
            set {
                _resultCollection = value;
                RaisePropertyChanged(() => ResultCollection);
            }
        }

        private ObservableCollection<DownloadInfo> _downloadQueue = new ObservableCollection<DownloadInfo>();
        public ObservableCollection<DownloadInfo> DownloadQueue
        {
            get { return _downloadQueue; }
            set {
                _downloadQueue = value;
                RaisePropertyChanged(() => DownloadQueue);
            }
        }
        #endregion

        #region Play
        private string _playUrl = string.Empty;
        public string PlayUrl
        {
            get { return _playUrl; }
            set {
                _playUrl = value;
                RaisePropertyChanged(() => PlayUrl);
            }
        }

        protected void Play()
        {
            player.Open(new Uri(PlayUrl));
        }
        #endregion

        #region Command
        public ICommand SearchCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return !string.IsNullOrEmpty(Keywords); },
                    ExecuteCallback = delegate {
                        CurrentIndex = 1;
                        client.DownloadStringAsync(new Uri(FullUri));
                    }
                };
            }
        }

        public ICommand PlayCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);
                    PlayUrl = ResultCollection.FirstOrDefault(i => i.id == id).src;
                    Play();
                });
            }
        }

        public ICommand DownloadCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    MusicInfo entity = (MusicInfo)t;
                    DownloadInfo downloadInfo = new DownloadInfo(entity.title + ".mp3", entity.src);
                    DownloadQueue.Add(downloadInfo);
                });
            }
        }

        public ICommand NextCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        CurrentIndex++;
                        client.DownloadStringAsync(new Uri(FullUri));
                    }
                };
            }
        }

        public ICommand PreviousCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return CurrentIndex > 1; },
                    ExecuteCallback = delegate {
                        CurrentIndex--;
                        client.DownloadStringAsync(new Uri(FullUri));
                    }
                };
            }
        }
        #endregion
    }
}
